package com.xn.app.muying.activity;

import android.app.AlertDialog;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.xn.app.muying.R;
import com.xn.app.muying.sqlite.DBManager;
import com.xn.app.muying.util.APIMethod;
import com.xn.app.muying.util.BaseActivity;
import com.xn.app.muying.util.MyAlertDialog;
import com.xn.app.muying.util.MyImageLoader;
import com.xn.app.muying.util.NetworkUtil;
import com.xn.app.muying.util.ToastUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Request;

/**
 * Created by Administrator on 2017/1/5.
 */
public class SheetUnexceptionInfoActivity extends BaseActivity implements View.OnClickListener {

    private ImageView report,status;
    private TextView tv;
    //数据库
    private DBManager db = null;
    /**
     * 图片缓存
     */
    private ImageLoader imageLoader = null;
    private DisplayImageOptions options = null;
    //加载框
    AlertDialog dialog;
    ScrollView scrollView;
    AlphaAnimation appearAnimation;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sheetunexception);
        db = new DBManager(this);
        imageLoader = MyImageLoader.getImageLoader(this);
        // DisplayImageOptions对象是对下载好以后的图片，在显示出来的时候做的设置
        options = new DisplayImageOptions.Builder().showImageOnLoading(0) // 在下载期间显示的图片
                .showImageForEmptyUri(0) // 设置图片Uri为空或是错误的时候显示的图片
                .showImageOnFail(0) // 设置图片加载或解码过程中发生错误显示的图片
                .bitmapConfig(Bitmap.Config.RGB_565) // 防止内存溢出的，图片太多就这这个
                .cacheInMemory(true).cacheOnDisc(true).build();
        initView();
    }

    private void initView() {
        appearAnimation = new AlphaAnimation(0, 1);
        appearAnimation.setFillAfter(true);
        appearAnimation.setDuration(200);
        scrollView = (ScrollView) findViewById(R.id.scrollView);
        TextView title_name = (TextView) findViewById(R.id.title_name);
        ImageView img_back = (ImageView) findViewById(R.id.img_back);
        report = (ImageView) findViewById(R.id.activity_sheetunexception_iv1);
        status = (ImageView) findViewById(R.id.activity_sheetunexception_iv2);
        tv = (TextView) findViewById(R.id.activity_sheetunexception_tv);
        title_name.setText("已解读");
        tv.setText("未发现指标异常");
        status.setImageResource(R.mipmap.weiyichang);
        img_back.setOnClickListener(this);
        if (NetworkUtil.isNetworkAvailable(SheetUnexceptionInfoActivity.this)) {
            dialog = new MyAlertDialog().ShowDialog(SheetUnexceptionInfoActivity.this, R.layout.dialog_loading);
            SheetInfo(getIntent().getStringExtra("id"));
        } else {
            ToastUtil.showToast(SheetUnexceptionInfoActivity.this, R.string.no_network_hint);
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.img_back:
                finish();
                break;
        }
    }


    private void SheetInfo(final String id) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Request request = new Request.Builder().url(APIMethod.SheetInfo(id)).addHeader("Authorization", db.select("token_type") + " " + db.select("access_token")).get().build();
                    okhttp3.Response response = MuYingApplication.mOkHttpClient.newCall(request).execute();
                    int code = response.code();
                    String bodys = response.body().string();
                    if (code == 204 || code == 200) {
                        Message msg2 = new Message();
                        msg2.what = 0;
                        msg2.obj = bodys;
                        handler.sendMessage(msg2);
                    } else {
                        Message msg1 = new Message();
                        msg1.what = 1;
                        msg1.arg1 = code;
                        msg1.obj = bodys;
                        handler.sendMessage(msg1);
                    }
                } catch (IOException e) {
                    e.printStackTrace();

                }
            }
        }).start();
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {

            switch (msg.what) {
                case 0:
                    onJsonData(msg.obj.toString());
                    break;
                case 1:
                    ToastUtil.showToast(SheetUnexceptionInfoActivity.this, "获取数据失败");
                    break;
            }
        }
    };

    private void onJsonData(String bobys) {
        try {
            JSONObject jsonObject = new JSONObject(bobys);
            final String reportUrl = jsonObject.optString("reportUrl");
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                        imageLoader.displayImage(reportUrl, report, options, new ImageLoadingListener() {
                            @Override
                            public void onLoadingStarted(String s, View view) {

                            }

                            @Override
                            public void onLoadingFailed(String s, View view, FailReason failReason) {
                                if (dialog != null) {
                                    dialog.dismiss();
                                }
                                scrollView.setVisibility(ScrollView.VISIBLE);
                                scrollView.startAnimation(appearAnimation);
                            }

                            @Override
                            public void onLoadingComplete(String s, View view, Bitmap bitmap) {
                                if (dialog != null) {
                                    dialog.dismiss();
                                }
                                scrollView.setVisibility(ScrollView.VISIBLE);
                                scrollView.startAnimation(appearAnimation);
                            }

                            @Override
                            public void onLoadingCancelled(String s, View view) {

                            }
                        });
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }
}
